package org.alwayssuper.protocol.commons.transform.realtimev2016.enums;

/**
 * 挡位枚举 (整车数据 0x01)
 * 基于 GB/T 32960.3-2016 标准
 * Bit7-Bit4: 驱动力制动力标志位
 * Bit3-Bit0: 挡位值
 * @author alwaysSuper
 */
public enum GearPosition {
    NEUTRAL(0x0000, "空挡"),
    GEAR_1(0x0001, "1挡"),
    GEAR_2(0x0002, "2挡"),
    GEAR_3(0x0003, "3挡"),
    GEAR_4(0x0004, "4挡"),
    GEAR_5(0x0005, "5挡"),
    GEAR_6(0x0006, "6挡"),
    GEAR_7(0x0007, "7挡"),
    GEAR_8(0x0008, "8挡"),
    GEAR_9(0x0009, "9挡"),
    GEAR_10(0x000A, "10挡"),
    GEAR_11(0x000B, "11挡"),
    GEAR_12(0x000C, "12挡"),
    REVERSE(0x000D, "倒挡"),
    AUTO_D(0x000E, "自动D挡"),
    PARKING(0x000F, "停车P挡"),
    INVALID(0x00FF, "无效");

    // 标志位定义
    public static final int DRIVING_FORCE_FLAG = 0x20;  // Bit5: 有驱动力
    public static final int BRAKING_FORCE_FLAG = 0x10;  // Bit4: 有制动力

    private final int code;
    private final String description;

    GearPosition(int code, String description) {
        this.code = code;
        this.description = description;
    }

    public int getCode() {
        return code;
    }

    public String getDescription() {
        return description;
    }

    /**
     * 从原始字节值解析挡位
     * @param rawValue 包含标志位的原始值
     * @return 挡位枚举
     */
    public static GearPosition fromRawValue(int rawValue) {
        int gearValue = rawValue & 0x0F; // 取低4位作为挡位值
        for (GearPosition gear : values()) {
            if ((gear.code & 0x0F) == gearValue) {
                return gear;
            }
        }
        return INVALID;
    }

    /**
     * 从挡位代码获取挡位枚举
     * @param code 挡位代码
     * @return 挡位枚举
     */
    public static GearPosition fromCode(int code) {
        for (GearPosition gear : values()) {
            if (gear.code == code) {
                return gear;
            }
        }
        return INVALID;
    }

    /**
     * 检查是否有驱动力
     * @param rawValue 原始值
     * @return true=有驱动力
     */
    public static boolean hasDrivingForce(int rawValue) {
        return (rawValue & DRIVING_FORCE_FLAG) != 0;
    }

    /**
     * 检查是否有制动力
     * @param rawValue 原始值
     * @return true=有制动力
     */
    public static boolean hasBrakingForce(int rawValue) {
        return (rawValue & BRAKING_FORCE_FLAG) != 0;
    }

    @Override
    public String toString() {
        return String.format("GearPosition{code=0x%04X, description='%s'}", code, description);
    }
}